<template>
  <div class="login-container">
    <div class="login-wrapper">
      <div class="login-form">
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          label-position="left"
          class="login-form"
        >
          <h3 class="title">系统登录</h3>
          <!-- 租户ID -->
          <el-form-item prop="tenantId" v-if="tenantEnabled">
            <el-select
              v-model="loginForm.tenantId"
              placeholder="请选择租户"
              size="large"
              style="width: 100%;"
            >
              <el-option
                v-for="(item, index) in tenantList"
                :key="index"
                :label="item.companyName"
                :value="item.tenantId"
              ></el-option>
            </el-select>
          </el-form-item>

          <!-- 用户名 -->
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="用户名"
              name="username"
              type="text"
              tabindex="1"
              auto-complete="on"
              size="large"
            />
          </el-form-item>

          <!-- 密码 -->
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              placeholder="密码"
              name="password"
              type="password"
              tabindex="2"
              auto-complete="on"
              size="large"
              show-password
            />
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item prop="code" v-if="captchaEnabled">
            <el-input
              v-model="loginForm.code"
              placeholder="验证码"
              name="code"
              type="text"
              tabindex="3"
              size="large"
            >
              <template #append>
                <img
                  :src="codeUrl"
                  @click="getCode"
                  class="login-code"
                  title="点击切换验证码"
                  alt="验证码"
                />
              </template>
            </el-input>
          </el-form-item>

          <!-- 记住密码 -->
          <el-form-item>
            <div class="flex items-center justify-between">
              <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
              <div class="login-link">
                <el-button type="text" @click="register" v-if="register">立即注册</el-button>
                <el-button type="text" @click="reset">忘记密码</el-button>
              </div>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              :loading="loading"
              type="primary"
              style="width: 100%"
              @click="handleLogin"
              size="large"
            >
              登 录
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 第三方登录 -->
        <div v-if="hasSocialLogin()" class="social-login">
          <span class="social-title">其他登录方式</span>
          <div class="social-icons">
            <el-button
              v-if="thirdLogin.type.includes('weixin')"
              circle
              class="social-icon weixin-icon"
              @click="doSocialLogin('weixin')"
            >
              <svg-icon icon-class="weixin" class="social-icon-size" />
            </el-button>
            <el-button
              v-if="thirdLogin.type.includes('maxkey')"
              circle
              class="social-icon maxkey-icon"
              @click="doSocialLogin('maxkey')"
            >
              <svg-icon icon-class="maxkey" class="social-icon-size" />
            </el-button>
            <el-button
              v-if="thirdLogin.type.includes('topiam')"
              circle
              class="social-icon topiam-icon"
              @click="doSocialLogin('topiam')"
            >
              <svg-icon icon-class="topiam" class="social-icon-size" />
            </el-button>
            <el-button
              v-if="thirdLogin.type.includes('gitee')"
              circle
              class="social-icon gitee-icon"
              @click="doSocialLogin('gitee')"
            >
              <svg-icon icon-class="gitee" class="social-icon-size" />
            </el-button>
            <el-button
              v-if="thirdLogin.type.includes('github')"
              circle
              class="social-icon github-icon"
              @click="doSocialLogin('github')"
            >
              <svg-icon icon-class="github" class="social-icon-size" />
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部版权信息 -->
<!--    <div class="copyright">-->
<!--      <div class="copyright-line">-->
<!--        <span>Copyright © 2019-2024 RuoYi-Vue-Plus</span>-->
<!--      </div>-->
<!--      <div class="copyright-line">-->
<!--        <span>开源地址:</span>-->
<!--        <a href="https://gitee.com/y_project/RuoYi-Vue-Plus" target="_blank">-->
<!--          https://gitee.com/y_project/RuoYi-Vue-Plus-->
<!--        </a>-->
<!--      </div>-->
<!--    </div>-->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/store/modules/user';
import { getTenantList, getCodeImg } from '@/api/login';
import type { LoginData, TenantVO } from '@/api/types';

// 暂时移除i18n以避免依赖问题
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 响应式数据
const loginFormRef = ref();
const loading = ref(false);
const codeUrl = ref('');
const captchaEnabled = ref(true); // 默认启用验证码
const tenantEnabled = ref(true); // 默认启用租户选择
const registerFlag = ref(false);
const redirect = ref('');
const tenantList = ref<TenantVO[]>([]);

// 登录表单
const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: ''
} as LoginData);

// 表单验证规则 - 使用计算属性确保动态更新
const loginRules = computed(() => ({
  tenantId: [{ required: tenantEnabled.value, trigger: 'change', message: '请选择租户' }],
  username: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
  password: [{ required: true, trigger: 'blur', message: '请输入密码' }],
  code: [{ required: captchaEnabled.value, trigger: 'change', message: '请输入验证码' }]
}));

// 刷新验证码的辅助函数
const refreshCaptcha = () => {
  if (captchaEnabled.value) {
    getCode();
  }
};

// 第三方登录
const thirdLogin = reactive({
  type: [] as string[]
});

// 计算属性
const hasSocialLogin = () => {
  return thirdLogin.type.length > 0;
};

// 方法
const handleLogin = async () => {
  if (!loginFormRef.value) return;
  await loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      try {
        // 记住密码
        if (loginFormRef.value.rememberMe && loginFormRef.value.username && loginFormRef.value.password) {
          localStorage.setItem('username', loginFormRef.value.username || '');
          localStorage.setItem('password', loginFormRef.value.password || '');
          localStorage.setItem('rememberMe', loginFormRef.value.rememberMe.toString());
        } else {
          localStorage.removeItem('username');
          localStorage.removeItem('password');
          localStorage.removeItem('rememberMe');
        }

        // 确保租户ID和验证码字段在登录对象中正确传递
        // 构建一个纯数据对象，避免响应式对象的循环引用
        const loginData = {
          username: loginFormRef.value.username,
          password: loginFormRef.value.password,
          rememberMe: loginFormRef.value.rememberMe,
          // 确保必填字段存在
          tenantId: tenantEnabled.value ? loginFormRef.value.tenantId : undefined,
          code: captchaEnabled.value ? loginFormRef.value.code : undefined,
          uuid: captchaEnabled.value ? loginFormRef.value.uuid : undefined
        };

        // 登录
        await userStore.login(loginData);

        // 登录成功，跳转页面
        router.replace({
          path: redirect.value || '/'
        });
      } catch (error) {
        // 登录失败时刷新验证码
        refreshCaptcha();
        console.error('登录失败:', error);
      } finally {
        loading.value = false;
      }
    }
  });
};

// 获取验证码
const getCode = async () => {
  try {
    const res = await getCodeImg();
    // 设置验证码图片和UUID
    codeUrl.value = res.data.img;
    loginFormRef.value.uuid = res.data.uuid;
    captchaEnabled.value = true;
  } catch (error) {
    console.error('获取验证码失败', error);
  }
};

// 获取本地存储的登录数据
const getLoginData = () => {
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginFormRef.value.username = username || '';
  loginFormRef.value.password = password || '';
  loginFormRef.value.rememberMe = rememberMe === 'true';
};

// 初始化租户列表
const initTenantList = async () => {
  try {
    // 调用API获取租户列表
    const res = await getTenantList(false);
    tenantList.value = res.data || [];
    tenantEnabled.value = tenantList.value.length > 1;
    if (tenantEnabled.value && tenantList.value.length > 0) {
      loginFormRef.value.tenantId = tenantList.value[0].tenantId;
    }
  } catch (error) {
    console.error('初始化租户列表失败', error);
    // 确保即使出现错误也有默认值
    tenantEnabled.value = true;
    tenantList.value = [
      { tenantId: '000000', companyName: '默认租户', domain: '' },
      { tenantId: '100000', companyName: '测试租户', domain: '' }
    ];
    loginFormRef.value.tenantId = '000000';
  }
};

// 注册
const register = () => {
  registerFlag.value = true;
  router.replace({
    path: '/register'
  });
};

// 重置密码
const reset = () => {
  router.replace({
    path: '/reset'
  });
};

// 执行第三方登录
const doSocialLogin = (type: string) => {
  window.location.href = import.meta.env.VITE_APP_BASE_API + `/auth/social/${type}/login?redirect=${encodeURIComponent(redirect.value || '/')}&clientId=${import.meta.env.VITE_APP_CLIENT_ID}`;
};

// 初始化
onMounted(() => {
  // 获取验证码
  getCode();
  // 获取本地存储的登录数据
  getLoginData();
  // 获取租户列表
  initTenantList();
  // 获取第三方登录配置
  // thirdLogin.type = ['weixin', 'maxkey', 'topiam', 'gitee', 'github'];
  // 获取重定向地址
  redirect.value = route.query.redirect ? String(route.query.redirect) : '';
});
</script>

<style lang="scss" scoped>
.login-container {
  width: 100%;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-size: cover;
  background-position: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.login-wrapper {
  width: 400px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 30px;
}

/* 进一步减小输入框之间的间距 */
.login-form .el-form-item {
  margin-bottom: 10px;
}

.title {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

.login-form {
  width: 100%;
}

.svg-container {
  padding: 6px 8px;
  color: #909399;
  display: inline-block;
}

.login-code {
  width: 100px;
  height: 36px;
  cursor: pointer;
  vertical-align: middle;
}

.login-link {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.social-login {
  margin-top: 20px;
  text-align: center;
}

.social-title {
  display: block;
  margin-bottom: 20px;
  color: #606266;
  font-size: 14px;
}

.social-icons {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.social-icon {
  width: 40px;
  height: 40px;
}

.social-icon-size {
  font-size: 20px;
}

.copyright {
  position: absolute;
  bottom: 20px;
  text-align: center;
  color: #fff;
  font-size: 12px;
  line-height: 1.5;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.copyright-line {
  margin-bottom: 5px;
}

.copyright a {
  color: #fff;
  text-decoration: none;
}

.copyright a:hover {
  text-decoration: underline;
}

// 响应式设计
@media (max-width: 768px) {
  .login-wrapper {
    width: 90%;
    margin: 0 auto;
  }
}
</style>
